const http = require('http'),
url = require('url'),
uuid = require('node-uuid'),
log = require('./log'),
errObj = {
	'01' : {
		errcode : '01',
		errmsg : '缺少参数'
	},
	'02' : {
		errcode : '02',
		errmsg : '参数不合法'
	}
},
appList = {
	'1' : {
		app_id : '1',
		app_secret : '123456'
	}
},
tokenList = [];

function queryToObj(query) {
	var queryList = query.split('&'),
	queryObj = {}
	queryList.forEach(query => {
		var kv = query.split('=');
		queryObj[kv[0]] = kv[1]
	})
	return queryObj
}

function getToken(req, res) {
	var urlObj = url.parse(req.url),
	resObj = {},
	queryObj = queryToObj(urlObj.query);
	res.writeHead(200, {
		"Content-Type" : "application/json"
	})
	if (!queryObj.app_id || !queryObj.app_secret) {
		resObj = errObj['01']
	} else if (!appList[queryObj.app_id] || queryObj.app_secret != appList[queryObj.app_id].app_secret) {
		resObj = errObj['02']
	} else {
		var app_id = queryObj.app_id,
		access_token;
		if (appList[app_id].access_token && appList[app_id].expires_in > new Date().getTime()) {
			access_token = appList[app_id].access_token
		} else {
			access_token = uuid.v4();
			appList[app_id].access_token = access_token;
			appList[app_id].expires_in = new Date().getTime() + 7200000;
			tokenList[access_token] = app_id;
		}
		resObj.access_token = access_token;
		resObj.expires_in = 7200
	}
	res.end(JSON.stringify(resObj))
}

function authorize(req, res) {
	var urlObj = url.parse(req.url),
	queryObj = queryToObj(urlObj.query);
	res.writeHead(200, {
		"Content-Type" : "text/html"
	})
	if (!queryObj.app_id || !queryObj.redirect_uri || !queryObj.response_type || !queryObj.scope || !queryObj.state) {
		res.end(JSON.stringify(errObj['01']))
	} else {
		res.end('登录')
	}
}

function getClientInfo(req, res) {
	var urlObj = url.parse(req.url),
	resObj = {},
	queryObj = queryToObj(urlObj.query);
	res.writeHead(200, {
		"Content-Type" : "application/json"
	})
	if (!queryObj.access_token || !queryObj.mobile) {
		resObj = errObj['01']
	} else if (!tokenList[queryObj.access_token] || appList[tokenList[queryObj.access_token]].expires_in < new Date().getTime()) {
		resObj = errObj['02']
	} else {
		resObj.isClient = Math.random() < 0.5
	}
	res.end(JSON.stringify(resObj))
}

http.createServer((req, res) => {
	new Promise((resolve, reject) => {
		if (req.method == 'GET') {
			var urlObj = url.parse(req.url);
			if (urlObj.pathname == '/api/getToken') {
				getToken(req, res)
			} else if (urlObj.pathname == '/oauth2/authorize') {
				authorize(req, res)
			} else if (urlObj.pathname == '/api/getClientInfo') {
				getClientInfo(req, res)
			} else {
				log('path unexists: ' + urlObj.pathname)
				reject()
			}
		} else {
			log('method unexists: ' + req.method)
			reject()
		}
	}).then(result => {}, result => {
		res.writeHead(404, {
			"Content-Type" : "text/html"
		})
		res.end("<h1>404 Not Found</h1>")
	}).catch(err => log(err))
}).listen(5000, () => log('listening 5000'))
